<template>
  <div>
    <el-dialog
      title="编辑大转盘活动"
      v-model="state.isShow"
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      align-center
      width="900px"
      @closed="closed"
    >
      <div class="h-[calc(100vh-200px)] overflow-hidden">
        <el-scrollbar ref="scrollbarRef" always class="h-full w-full overflow-hidden">
          <ul>
            <li class="flex items-center rounded-[6px]">
              <div class="w-[120px] pl-2 flex item justify-end">
                <span>活动状态</span>
                <span class="mt-[-1px] mx-[4px]">:</span>
              </div>
              <div class="flex-1 w-0 ml-[15px]">
                <el-radio-group v-model="form.Status">
                  <el-radio :value="1" size="large">开启</el-radio>
                  <el-radio :value="0" size="large">关闭</el-radio>
                </el-radio-group>
              </div>
            </li>
            <li class="flex items-center rounded-[6px]">
              <div class="w-[120px] pl-2 flex item justify-end">
                <span>抽奖方式</span>
                <span class="mt-[-1px] mx-[4px]">:</span>
              </div>
              <div class="flex-1 w-0 ml-[15px]">
                <el-radio-group v-model="form.Way">
                  <el-radio :value="0" size="large">当日抽</el-radio>
                  <el-radio :value="1" size="large">隔日抽</el-radio>
                </el-radio-group>
              </div>
            </li>
            <li class="flex items-center rounded-[6px] mb-[5px]">
              <div class="w-[120px] pl-2 flex item justify-end">
                <span>发放方式</span>
                <span class="mt-[-1px] mx-[4px]">:</span>
              </div>
              <div class="flex-1 w-0 ml-[15px]">
                <el-radio-group v-model="form.GiveMethod">
                  <el-radio :value="0" size="large">自动发放</el-radio>
                  <el-radio :value="1" size="large">人工审核</el-radio>
                </el-radio-group>
              </div>
            </li>
            <li class="flex items-center rounded-[6px] mb-[15px]">
              <div class="w-[120px] pl-2 flex item justify-end">
                <span>抽奖时间</span>
                <span class="mt-[-1px] mx-[4px]">:</span>
              </div>
              <div class="flex-1 w-0 ml-[15px]">
                <el-time-picker
                  class="!w-[120px]"
                  v-model="form.StartTime"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="开始时间"
                />
                <span>-</span>
                <el-time-picker
                  class="!w-[120px]"
                  v-model="form.EndTime"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="结束时间"
                />
              </div>
            </li>
            <li class="flex items-center rounded-[6px] mb-[15px]">
              <div class="w-[120px] pl-2 flex item justify-end">
                <span>排序</span>
                <span class="mt-[-1px] mx-[4px]">:</span>
              </div>
              <div class="flex-1 w-0 ml-[15px]">
                <el-input-number
                  v-model="form.Sort"
                  class="!w-[246px]"
                  :min="0"
                  controls-position="right"
                />
              </div>
            </li>
            <li class="flex items-center rounded-[6px] mb-[15px]">
              <div class="w-[120px] pl-2 flex items-center justify-end">
                <span>活动广告图片</span>
                <el-tooltip effect="dark" content="建议尺寸：710*260" placement="top-start">
                  <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
                </el-tooltip>
                <span class="mt-[-3px] mx-[4px]">:</span>
              </div>
              <div class="flex-1 w-0 ml-[15px] overflow-hidden">
                <BannerPreview
                  @delete="form.ActivityImg = ''"
                  v-if="form.ActivityImg"
                  :src="form.ActivityImg"
                />
                <div v-else class="w-[100px] h-[100px]" v-loading="state.aloading">
                  <el-upload
                    ref="uploadRef"
                    drag
                    action="#"
                    accept="image/jpeg,image/png,image/jpg"
                    :show-file-list="false"
                    :multiple="false"
                    :limit="1"
                    :http-request="(e: any) => UploadImage(e, 1)"
                    :before-upload="beforePicUpload"
                  >
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </div>
              </div>
            </li>
            <li class="flex items-center rounded-[6px] mb-[15px]">
              <div class="w-[120px] pl-2 flex items-center justify-end">
                <span>活动内容图片</span>
                <el-tooltip effect="dark" content="建议尺寸：710" placement="top-start">
                  <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
                </el-tooltip>
                <span class="mt-[-3px] mx-[4px]">:</span>
              </div>
              <div class="flex-1 w-0 ml-[15px] overflow-hidden">
                <BannerPreview
                  @delete="form.ContentImg = ''"
                  v-if="form.ContentImg"
                  :src="form.ContentImg"
                />
                <div v-else class="w-[100px] h-[100px]" v-loading="state.cloading">
                  <el-upload
                    ref="uploadRef"
                    drag
                    action="#"
                    accept="image/jpeg,image/png,image/jpg"
                    :show-file-list="false"
                    :multiple="false"
                    :limit="1"
                    :http-request="(e: any) => UploadImage(e, 2)"
                    :before-upload="beforePicUpload"
                  >
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </div>
              </div>
            </li>
            <li class="mb-[15px] w-[130px] text-right">活动条件参数设定：</li>
            <li class="mb-[15px]">
              <el-alert
                title="所有奖品的中奖几率，加起来必须是100%"
                type="warning"
                show-icon
                :closable="false"
              />
            </li>
            <li class="mb-[15px]" v-loading="state.loading">
              <el-tabs v-model="state.tabActive" type="card">
                <el-tab-pane :label="item.Name" :name="i" v-for="(item, i) in form.Config">
                  <div class="flex items-center mt-[15px] ml-[15px]">
                    <div>单次抽奖流水：</div>
                    <el-input-number
                      v-model="item.BetAmount"
                      class="!w-[200px] mr-[10px]"
                      :min="0"
                      controls-position="right"
                    />
                    <el-checkbox
                      label="启用"
                      v-model="item.Status"
                      :true-value="1"
                      :false-value="0"
                    />
                  </div>
                  <div class="p-[15px]">
                    <el-table scrollbar-always-on :data="item.RewardConfig" border stripe>
                      <template #empty>
                        <ui-empty />
                      </template>
                      <el-table-column align="center" prop="Name" label="序号" width="80">
                        <template #default="{ row }: TableItem">
                          {{ row.Sort }}
                        </template>
                      </el-table-column>
                      <el-table-column align="center" prop="RewardType" label="奖品类型">
                        <template #default="{ row }: TableItem">
                          {{ row.RewardType == 1 ? "奖金" : "奖品" }}
                        </template>
                      </el-table-column>
                      <el-table-column align="center" prop="RewardAmount" label="奖品">
                        <template #default="{ row }: TableItem">
                          {{ row.RewardAmount }}
                        </template>
                      </el-table-column>
                      <el-table-column
                        align="center"
                        prop="RewardRemark"
                        label="奖品备注"
                        show-overflow-tooltip
                      >
                        <template #default="{ row }: TableItem">
                          {{ row.RewardRemark || "--" }}
                        </template>
                      </el-table-column>
                      <el-table-column align="center" prop="Name" label="中奖几率(%)">
                        <template #default="{ row }: TableItem"> {{ row.Rate }}% </template>
                      </el-table-column>
                      <el-table-column align="center" prop="Count" label="中奖数量">
                        <template #default="{ row }: TableItem">
                          {{ row.Count }}
                        </template>
                      </el-table-column>
                      <el-table-column align="center" prop="Name" label="中奖启用">
                        <template #default="{ row }: TableItem">
                          <el-dropdown
                            placement="bottom"
                            @command="(e: number) => handleChangeStatus(row, e)"
                          >
                            <el-button v-if="row.Status == 1" type="success" size="small">
                              启用
                            </el-button>
                            <el-button v-else type="danger" size="small">禁用</el-button>
                            <template #dropdown>
                              <el-dropdown-menu>
                                <el-dropdown-item :disabled="row.Status == 1" :command="1">
                                  <div class="w-full text-center">启用</div>
                                </el-dropdown-item>
                                <el-dropdown-item :disabled="row.Status == 0" :command="0">
                                  <div class="w-full text-center">禁用</div>
                                </el-dropdown-item>
                              </el-dropdown-menu>
                            </template>
                          </el-dropdown>
                        </template>
                      </el-table-column>
                      <el-table-column align="center" label="操作" width="130">
                        <template #default="{ row, $index }: TableItem">
                          <el-button type="primary" size="small" @click="handleEdit(row, $index)">
                            编辑
                          </el-button>
                          <el-button type="danger" size="small" @click="handleDel(item, $index)">
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <div class="flex justify-center items-center pb-[15px]">
                    <el-button type="primary" @click="handleAdd(item)">添加</el-button>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </li>
          </ul>
        </el-scrollbar>
      </div>
      <template #footer>
        <el-button @click="closed">取 消</el-button>
        <el-button
          :disabled="state.updating"
          :loading="state.updating"
          type="primary"
          @click="handleSubmit"
        >
          确 定
        </el-button>
        <el-button
          :disabled="state.loading"
          :loading="state.loading"
          type="primary"
          @click="handleReset"
        >
          重置数据
        </el-button>
      </template>
    </el-dialog>
    <EditTurntableDialog
      ref="editTurntableDialogRef"
      :data="rewardData"
      @update="handleAddUpdate"
    />
  </div>
</template>
<script setup lang="ts">
import BannerPreview from "@/components/banner-preview.vue";
import EditTurntableDialog from "./edit-turntable-dialog.vue";
import { reqUploadImg } from "@/api/user";
import { message } from "@/utils/message";
import { reqActivityDiscountEdit, reqActivityDiscountReset } from "@/api/activity";
import { cloneDeep } from "lodash-es";

interface TableItem {
  row: DiscountRewardConfig;
  $index: number;
}

const props = withDefaults(
  defineProps<{
    data: ActivityDiscountMo | null;
  }>(),
  {}
);
const emit = defineEmits(["update"]);
const uploadRef = ref();
const scrollbarRef = ref();
const editTurntableDialogRef = ref();
const rewardData = ref<DiscountRewardConfig | null>(null);
const rewardIndex = ref<number | null>(null);
const state = reactive({
  isShow: false,
  loading: false,
  aloading: false,
  cloading: false,
  updating: false,
  tabActive: 0
});
const form = ref<Partial<ActivityDiscountMo>>({
  Status: 0,
  Way: 1,
  GiveMethod: 0,
  Sort: 0,
  Config: [],
  StartTime: "",
  EndTime: "",
  ActivityImg: "",
  ContentImg: "",
  ActivityUrl: ""
});
const closed = () => {
  state.isShow = false;
};
const open = () => {
  if (props.data) {
    form.value = cloneDeep(props.data);
  }
  state.isShow = true;
  setTimeout(() => {
    scrollbarRef.value?.setScrollTop?.(0);
  }, 100);
};

const UploadImage = async (e: any, type = 1) => {
  try {
    if (type == 1) {
      state.aloading = true;
    } else {
      state.cloading = true;
    }
    let params = new FormData();
    params.append("ImgPath", e.file);
    let res = await reqUploadImg(params);
    state.aloading = false;
    state.cloading = false;
    if (type == 1) {
      form.value.ActivityImg = "/" + res.data.ImgPath;
    } else {
      form.value.ContentImg = "/" + res.data.ImgPath;
    }
    uploadRef.value?.clearFiles();
  } catch (error) {
    state.aloading = false;
    state.cloading = false;
    uploadRef.value?.clearFiles();
    console.log(error);
  }
};

const beforePicUpload = (file: any) => {
  const isIMAGE = file.type === "image/jpeg" || "image/jpg" || "image/png";
  const isLt200K = file.size / 1024 < 200;

  if (!isIMAGE) {
    message.warning("上传文件只能是图片格式!");
  }
  if (!isLt200K) {
    message.warning("上传头像图片大小不能超过 200KB!");
  }
  return isIMAGE && isLt200K;
};

// 添加奖品
const handleAdd = (item: DiscountConfig) => {
  if (item.RewardConfig.length >= 8) {
    message.warning("最多添加8个奖品");
    return;
  }
  rewardData.value = null;
  rewardIndex.value = null;
  nextTick(() => {
    editTurntableDialogRef.value?.open();
  });
};

// 编辑奖品
const handleEdit = (row: DiscountRewardConfig, index: number) => {
  rewardData.value = row;
  rewardIndex.value = index;
  nextTick(() => {
    editTurntableDialogRef.value?.open();
  });
};

// 删除奖品
const handleDel = (item: DiscountConfig, index: number) => {
  item.RewardConfig.splice(index, 1);
};

// 更新奖品
const handleAddUpdate = (row: DiscountRewardConfig, type: "add" | "edit") => {
  const newForm = cloneDeep(form.value);
  console.log(row);
  if (type == "add") {
    newForm.Config![state.tabActive].RewardConfig.push(cloneDeep(row));
  } else {
    if (rewardIndex.value == null) return;
    newForm.Config![state.tabActive].RewardConfig[rewardIndex.value] = cloneDeep(row);
  }
  form.value = cloneDeep(newForm);
};

const handleReset = async () => {
  try {
    state.loading = true;
    const res = await reqActivityDiscountReset();
    form.value = cloneDeep({
      ...form.value,
      Config: res.data
    });
    state.loading = false;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const handleChangeStatus = (row: DiscountRewardConfig, key: number) => {
  row.Status = key;
};

// 提交
const handleSubmit = async () => {
  if (!form.value.Config || form.value.Config.length == 0) return;
  if (!form.value.Sort && form.value.Sort != 0) {
    message.warning("请输入排序");
    return;
  }
  if (!form.value.ActivityImg) {
    message.warning("请上传活动图片");
    return;
  }
  for (let i = 0; i < form.value.Config.length; i++) {
    const openData = form.value.Config[i].RewardConfig.filter(item => item.Status == 1);
		const rate = form.value.Config[i].RewardConfig.reduce((total, item) => {
			return total + Number(item.Rate);
		}, 0)
		if(form.value.Config[i].RewardConfig.length == 7) {
			message.warning(`${form.value.Config[i].Name}请配置6或8个奖品，需为双数`);
      return;
		}
    if (form.value.Config[i].RewardConfig.length < 6 || openData.length < 6) {
      message.warning(`${form.value.Config[i].Name}最少配置且启用6个奖品，最多配置启用8个奖品`);
      return;
    }
		if(rate < 100) {
			message.warning(`${form.value.Config[i].Name}所有奖品的中奖几率，加起来必须是100%`);
      return;
		}
  }
  state.updating = true;
  const params = { ...form.value };
  delete params.Updating;
  delete params.Loading;
  delete params.Checked;
  delete params.Deleteing;
  try {
    await reqActivityDiscountEdit(params);
    message.success("修改大转盘活动成功");
    state.updating = false;
    emit("update");
    setTimeout(() => {
      closed();
    }, 200);
  } catch (error) {
    state.updating = false;
    console.log(error);
  }
};

defineExpose({
  open
});
</script>
<style scoped lang="scss">
:deep() {
  .el-dialog__body {
    padding: 20px;
  }
  .el-table__cell .cell {
    padding: 0 4px !important;
  }
  .el-input-number .el-input__inner {
    text-align: left !important;
  }
}
</style>
